package com.tuling.pool;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务线程池
 * ScheduledThreadPoolExecutor
 *      使用多线程执行任务，不会相互阻塞
 *      如果线程失活，会新建线程执行任务
 *      线程抛异常，任务会被抛弃，需要做捕获处理
 * SingleThreadScheduledExecutor
 *      单线程的ScheduledThreadPoolExecutor
 *      适用于需要后台线程执行周期任务，同时需要保证任务顺序执行
 */
public class ScheduleThreadPoolTest {

    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        for (int i = 0; i < 2; i++) {
            // scheduledThreadPool.schedule(new MyTask("task-" + i), 0, TimeUnit.SECONDS);
            scheduledThreadPool.scheduleAtFixedRate(new MyTask("task-" + i), 0, 2, TimeUnit.SECONDS);
        }
    }
}

class MyTask implements Runnable {
    private String name;

    public MyTask(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        try {
            System.out.println("name：" + name + ", startTime：" + new Date());
            Thread.sleep(3000);
            System.out.println("name：" + name + ", endTime：" + new Date());
            // 线程池执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}